package com.gking.processHarvest.service.Friends;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gking.processHarvest.common.BaseContext;
import com.gking.processHarvest.common.CustomException;
import com.gking.processHarvest.common.Res;
import com.gking.processHarvest.dto.PageFriendDto;
import com.gking.processHarvest.dto.VerifyAddFrindDto;
import com.gking.processHarvest.entity.Friends;
import com.gking.processHarvest.entity.Master;
import com.gking.processHarvest.entity.ShareProject;
import com.gking.processHarvest.mapper.FriendsMapper;
import com.gking.processHarvest.service.Master.MasterService;
import com.gking.processHarvest.service.ShareProject.ShareProjectService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;


@Slf4j
@Service
@Scope(value = "prototype", proxyMode = ScopedProxyMode.TARGET_CLASS)//三级缓存解决bean循环注入问题
public class FriendsServiceImpl extends ServiceImpl<FriendsMapper, Friends> implements FriendsService {

    @Autowired
    private MasterService masterService;

    @Autowired
    private ShareProjectService shareProjectService;

    @Autowired
    private FriendsService friendsService;


    /**
     * 搜索要添加的账号
     *
     * @param account 好友用户account
     * @return s
     */
    @Override
    public Res<VerifyAddFrindDto> search(String account) {
        if (account == null || account.equals("")) return Res.error("请将参数补充完整！");

        //查看用户是否存在
        LambdaQueryWrapper<Master> lambdaQueryWrapper = new LambdaQueryWrapper<>();
//        lambdaQueryWrapper.eq(Master::getAccount, account);
        lambdaQueryWrapper.apply("binary account = {0}", account);
        Master user = masterService.getOne(lambdaQueryWrapper);
        if (user == null) return Res.error("添加的用户不存在！");
        if (user.getId().equals(BaseContext.getCurrentId())) return Res.error("无法添加自己为好友！！");

        VerifyAddFrindDto verifyAddFrindDto = new VerifyAddFrindDto();

        //查看用户是否已经添加了
        LambdaQueryWrapper<Friends> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Friends::getFriendId, user.getId());
        queryWrapper.eq(Friends::getMasterId, BaseContext.getCurrentId());
        if (this.getOne(queryWrapper) != null) verifyAddFrindDto.setIsAdd(true);
        else verifyAddFrindDto.setIsAdd(false);

        user.setPassword("");
        user.setId("");
        verifyAddFrindDto.setMaster(user);

        return Res.success("查询用户成功！", verifyAddFrindDto);
    }


    /**
     * 添加好友
     *
     * @param account 好友用户账号
     * @return s
     */
    @Override
    public Res<String> add(String account) {
        if (account == null || account.equals("")) return Res.error("请将参数补充完整！");

        //查看用户是否存在
        LambdaQueryWrapper<Master> lambdaQueryWrapper = new LambdaQueryWrapper<>();
//        lambdaQueryWrapper.eq(Master::getAccount, account);
        lambdaQueryWrapper.apply("binary account = {0}", account);
        Master user = masterService.getOne(lambdaQueryWrapper);
        if (user == null) return Res.error("添加的用户不存在！");

        //查看用户是否已经添加了
        LambdaQueryWrapper<Friends> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Friends::getFriendId, user.getId());
        queryWrapper.eq(Friends::getMasterId, BaseContext.getCurrentId());
        if (this.getOne(queryWrapper) != null) return Res.error("好友已存在，请勿重复添加！");

        LambdaQueryWrapper<Master> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Master::getId, BaseContext.getCurrentId());
        Master master = masterService.getOne(wrapper);

        //没有则添加
        Friends friends = new Friends();
        friends.setFriendId(user.getId());
        this.save(friends);

        return Res.success("添加好友成功！");
    }


    /**
     * 删除好友
     *
     * @param id 好友用户id
     * @return s
     */
    @Override
    public Res<String> delete(String id) {
        if (id == null || id.equals("")) return Res.error("请将参数补充完整");

        //查询是否存在该好友
        LambdaQueryWrapper<Friends> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Friends::getFriendId, id);
        queryWrapper.eq(Friends::getMasterId, BaseContext.getCurrentId());
        if (this.getOne(queryWrapper) == null) Res.error("不存在该好友，无法删除！");

        //存在则删除
        this.remove(queryWrapper);

        try {
            //并将共享项目删除
            LambdaQueryWrapper<ShareProject> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(ShareProject::getFriendId, id);
            wrapper.eq(ShareProject::getMasterId, BaseContext.getCurrentId());
            shareProjectService.list(wrapper).forEach(item -> shareProjectService.delete(id, item.getProjectId()));
        } catch (Exception e) {
            throw new CustomException("删除好友成功，但是在删除与好友分享的项目时出现未知错误");
        }

        return Res.success("删除成功！");
    }


    /**
     * 获取好友列表
     *
     * @param page     页码
     * @param pageSize 大小
     * @param type     类型 0 为用户关注好友  1为用户粉丝好友
     * @return s
     */
    @Override
    public Res<Page> get(int type, Integer page, Integer pageSize) {
        LambdaQueryWrapper<Friends> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(Friends::getCreateTime);
        //通过条件判断进行分页查询，0 是查询用户关注的好友， 1是用户粉丝好友
        if (type == 0) queryWrapper.eq(Friends::getMasterId, BaseContext.getCurrentId());
        else queryWrapper.eq(Friends::getFriendId, BaseContext.getCurrentId());

        Page<Friends> pageInfo = new Page<>(page, pageSize);
        Page<Friends> pageData = this.page(pageInfo, queryWrapper);

        //遍历进行查看好友关注自身情况，并返回结果
        List<PageFriendDto> pageFriendDtoList = pageData.getRecords().stream().map(item -> {

            PageFriendDto pageFriendDto = new PageFriendDto();
            pageFriendDto.setCreateTime(item.getCreateTime());
            pageFriendDto.setFriendId(item.getFriendId());
            pageFriendDto.setId(item.getId());
            pageFriendDto.setMasterId(item.getMasterId());

            LambdaQueryWrapper<Friends> wrapper = new LambdaQueryWrapper<>();
            if (type == 0) {
                //好友是否关注了我
                wrapper.eq(Friends::getMasterId, item.getFriendId());
                wrapper.eq(Friends::getFriendId, BaseContext.getCurrentId());
            } else {
                //我是否关注了粉丝
                wrapper.eq(Friends::getMasterId, BaseContext.getCurrentId());
                wrapper.eq(Friends::getFriendId, item.getMasterId());
            }
            //如果查询到了结果，则相互关注
            pageFriendDto.setMutual(this.getOne(wrapper) != null);

            LambdaQueryWrapper<Master> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            if (type == 0) {
                lambdaQueryWrapper.eq(Master::getId, item.getFriendId());
                Master info = masterService.getOne(lambdaQueryWrapper);
                pageFriendDto.setFriendNickname(info.getNickname());
                pageFriendDto.setFriendAvatar(info.getAvatar());
            } else {
                lambdaQueryWrapper.eq(Master::getId, item.getMasterId());
                Master info = masterService.getOne(lambdaQueryWrapper);
                pageFriendDto.setMasterNickname(info.getNickname());
                pageFriendDto.setMasterAvatar(info.getAvatar());
            }

            return pageFriendDto;
        }).collect(Collectors.toList());

        //设置好信息
        Page<PageFriendDto> pageResult = new Page<>();
        pageResult.setRecords(pageFriendDtoList);
        pageResult.setSize(pageData.getSize());
        pageResult.setTotal(pageData.getTotal());
        pageResult.setPages(pageData.getPages());

        return Res.success("查找成功", pageResult);
    }


    /**
     * 获取好友信息
     *
     * @param friendId 好友id
     * @return s
     */
    @Override
    public Res<Master> friendInfo(String friendId) {
        LambdaQueryWrapper<Friends> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(Friends::getMasterId, BaseContext.getCurrentId());
        queryWrapper1.eq(Friends::getFriendId, friendId);

        if (friendsService.getOne(queryWrapper1) == null) {
            LambdaQueryWrapper<Friends> queryWrapper2 = new LambdaQueryWrapper<>();
            queryWrapper2.eq(Friends::getMasterId, friendId);
            queryWrapper2.eq(Friends::getFriendId, BaseContext.getCurrentId());
            if (friendsService.getOne(queryWrapper2) == null) return Res.error("你没有关注他，他也没有关注你");
        }

        LambdaQueryWrapper<Master> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Master::getId, friendId);
        Master master = masterService.getOne(wrapper);
        master.setPassword("");
        master.setAccount("");
        return Res.success("获取成功！", master);
    }
}
